<template>
  <!-- 分类组件 -->
  <Category
    style="margin-bottom: 20px"
    :isActive="isActive" />
  <!-- 底部表格结构 -->
  <div v-show="isActive == 0">
    <el-card
      style="margin-top: 20px"
      v-show="AttList.length > 0">
      <!-- 左上角添加属性按钮 -->
      <el-button type="success" style="margin-bottom: 20px" :disabled="!!!useCategory.c3Id" @click="check">添加属性</el-button>
      <!-- 表格结构 -->
      <el-table :data="AttList" width="500px" border>
        <el-table-column label="序号" type="index" width="100px"></el-table-column>
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-tag v-for="attr in row.attrValueList" :key="attr.id" style="margin: 8px" hit :type=" attr.id % 2 == 0 ? 'success' : 'danger'"
              size="default">
              {{ attr.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="属性操作">
          <template #="{ row, $index }">
            <el-button :icon="Edit" type="success" @click="updateAttr(row,$index)"></el-button>
            <!-- 删除 -->
            <el-button :icon="Delete" type="danger" @click="DeleteAttr(row)"></el-button></template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 底部暂无数据 -->
    <el-card>
      <!-- !!!强转为布尔类型 -->
      <el-empty
        description="暂无数据"
        v-show="!AttList.length"
        image="https://img.zcool.cn/community/01aa925b890fc3a80120245cd2ccfb.gif"
        :image-size="600" />
    </el-card>
  </div>

  <div v-show="isActive == 1">
    <!-- 卡片 -->
    <el-card>
      <!-- 表单 -->
      <el-form>
        <el-form-item label="属性名称">
          <el-input
            style="width: 150px"
            v-model="AttrParams.attrName"></el-input>
        </el-form-item>
        <el-button
          type="primary"
          :icon="Plus"
          @click="addAttr"
          :disabled="AttrParams.attrName ? false : true"
          >添加属性值</el-button
        >
        <el-button @click="goback">取消</el-button></el-form
      >
      <!-- 表格                             :data="AttrParams.attrValueList把新增的属性值添加到表格中                           -->
      <el-table
        style="margin-bottom: 11px"
        :data="AttrParams.attrValueList">
        <el-table-column
          label="序号"
          type="index"></el-table-column>

        <el-table-column label="属性值">
          <template #="{ row, $index }">
            <el-input
              size="small"
              ref="inputValue"
              v-model="row.valueName"
              style="font-size: 14px"
              v-if="row.showInput"
              @blur="showinp(row, $index)"></el-input>
            <div v-else @click="Check(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #="{ row, $index }">
            <!-- 删除气泡确认框 -->
            <el-popconfirm
              :title="`你确定要删除${row.valueName}吗?`"
              @confirm="deleteAttr($index)">
              <template #reference>
                <el-button
                  :icon="Delete"
                  type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column> </el-table
      ><el-button
        type="primary"
        @click="saveAttr"
        :disabled="!!!AttrParams.attrValueList.length"
        >保存</el-button
      >
      <el-button @click="goback">取消</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入深拷贝
import cloneDeep from 'lodash/cloneDeep'
import { reqAttr } from '@/api/product/attr/index';
import {ref, onMounted,watch,reactive,nextTick,} from 'vue';
import {Plus,Delete,Edit,} from '@element-plus/icons-vue';
import { reqAddOrUpdateAttr,reqDeleteAttr } from '@/api/product/attr/index';
import type {AttrList,Attr1, AttrValue,} from '@/api/product/attr/types';
import UseCategoryStore from '@/stores/category';
import { ElMessage } from 'element-plus';
let useCategory = UseCategoryStore();
// 定义起始数据
let AttList = ref<AttrList>([]);
// 显示与隐藏切换页面(默认是无数据界面,点击修改为添加属性)
let isActive = ref(0);
//
let inputValue = ref();
// 发请求获取三级分类下的数据
const getAttrlist = async () => {
  // 准备参数(一级二级三级数据的id携带)
  let { c1Id, c2Id, c3Id } = useCategory;
  // AttrList定义返回回来的数据类型
  let res: AttrList = await reqAttr(
    c1Id as number,
    c2Id as number,
    c3Id as number
  );
  // 赋值给初始数据
  AttList.value = res;
  // console.log(res)
};

// 监听三级分类的id如果有发生变化,就发请求获取数据(渲染下方的表格部分)
watch(() => useCategory.c3Id,() => {
    // 调用函数发请求
    getAttrlist();
  }
);

// 清空上一次输入的属性值
let reset = ()=>{
  Object.assign(AttrParams,{
  categoryLevel: 3,
  attrName: '',
  attrValueList: [],
})
}

// 点击切换到添加属性页面
let check = () => {
  // 调用函数清空上一次的属性值
  reset()
  isActive.value = 1;
  // 把id改变成点击的id
  AttrParams.categoryId = useCategory.c3Id as number;
};
// 点击返回到属性管理页面
let goback = () => {
  isActive.value = 0;
};

// 收集参数(新增属性)
let AttrParams = reactive<Attr1>({
  categoryLevel: 3,
  categoryId: 0,
  attrName: '',
  attrValueList: [],
});

// 添加属性值的回调
let addAttr = () => {
  // 动态给数组中增加一个对象 :key是后端规定的为valueName value是收集到的参数
  AttrParams.attrValueList.push({
    valueName: '',
    // 点击切换input和div
    showInput: true,
  });
  nextTick(() => {
    // 切换后获取最新的div元素使其焦点聚焦
    inputValue.value.focus();
  });
};

// 失去焦点的回调
let showinp = (row: AttrValue, index: number) => {
  // 判断入股属性值为空,提示信息
  if (row.valueName.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性不能为空',
    });
    // 如果属性值为空失去焦点后删除
    AttrParams.attrValueList.splice(index, 1);
  }
  // div和input来回切换
  row.showInput = false;

  // 遍历数组找到是否存才相同的属性值
  let repeat = AttrParams.attrValueList.find(
    (item: AttrValue) => {
      if (row != item) {
        return row.valueName === item.valueName;
      }
    }
  );
  if (repeat) {
    ElMessage({type: 'info',message: '属性值不能重复'});
    // 通过数组的splice将选中的下标切除掉
  AttrParams.attrValueList.splice(index, 1);
  }
};

// 切换为div的回调
let Check = (row: AttrValue, $index: number) => {
  // 点击切换为div
  row.showInput = true;
  // 获取最新的div元素使其聚焦
  nextTick(() => {
    inputValue.value.focus();
  });
};


// 发送请求添加属性值
let saveAttr = async () => {
  try {
    await reqAddOrUpdateAttr(AttrParams)
    //  跳转页面
    isActive.value = 0;
    // 提示信息
    ElMessage({type: 'success',message: '添加成功'});
    // 发请求获取最新的数据
    getAttrlist();
  } catch (error) {}
};

// 删除属性值的回调
let deleteAttr = (index: number) => {
  // 通过数组的splice将选中的下标切除掉
  AttrParams.attrValueList.splice(index, 1);
};

// 点击更新属性按钮的回调
let updateAttr = (row:AttrValue,index:number) => {
    isActive.value = 1;
    Object.assign(AttrParams,cloneDeep(row))
};

// 点击山区属性的回调
let DeleteAttr = async function(row:AttrValue){
   await reqDeleteAttr(row.id as number).then(()=>{
      ElMessage({
        type:'success',
        message:'删除成功!'
      })
      // 调用函数发请求获取最新数据
      getAttrlist();
   }).catch(()=>{
    ElMessage({
        type:'error',
        message:'删除失败,请稍后重试!'
      })
   })
  
    
}








</script>

<script lang="ts">
export default {
  name: 'Attr',
};
</script>

<style scoped></style>
